package com.yzr.service.impl;

import cn.hutool.core.io.FileUtil;
import com.yzr.service.DocumentService;
import com.yzr.util.FileType;
import com.yzr.util.IOUtil;
import com.yzr.util.converter.Conversion;
import com.yzr.util.converter.ConversionFactory;
import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.office.OfficeException;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @description
 * @author: yzr
 * @date: 2021/10/26 14:46
 **/
@Service
@Slf4j
public class DocumentServiceImpl implements DocumentService {

    private final ConversionFactory conversionFactory;

    public DocumentServiceImpl(ConversionFactory conversionFactory) {
        this.conversionFactory = conversionFactory;
    }

    @Override
    public void conversion(String from, String to) throws OfficeException {
//        try {
//            documentConverter.convert(new File(from))
//                    .to(new File(to))
//                    .as(DefaultDocumentFormatRegistry.PDF)
//                    .execute();
//        } catch (OfficeException e) {
//            e.printStackTrace();
//        }


        log.info("from:{}---->to:{}", from, to);
    }

    @Override
    public void view(String from, String to, HttpServletResponse response) throws FileNotFoundException {
        // 校验文件的类型是否是可转换的类型
        // 获得文件后缀：1.校验文件是否存在
        final File file = FileUtil.file(from);
        if (!FileUtil.isFile(file)) throw new FileNotFoundException("文件不存在");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            // 获取枚举类型
            Conversion instance = conversionFactory.getInstance(FileType.attribution(from));
            IOUtil.copy(new FileInputStream(instance.convert(from, to)), outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
